package com.cxm.weilai.util;

import okhttp3.*;

import java.io.IOException;
import java.util.Map;

/**
 * 〈一句话功能简述〉<br>
 * 〈〉
 *
 * @author Chenman
 * @create 2019/6/19
 * @since 1.0.0
 */
public class OkHttpRequest {
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    public static final MediaType DATA_FORM = MediaType.parse("application/x-www-form-urlencoded; charset=utf-8");
    OkHttpClient client = new OkHttpClient();
    public String get(String url) throws IOException {
        Request request = new Request.Builder()
                .url(url)
                .build();

        Response response = client.newCall(request).execute();
        return response.body().string();
    }

    public String postJson(String url, String json) throws IOException {
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
//                .addHeader("token","aaaa")
                .build();

        Response response = client.newCall(request).execute();
        return response.body().string();
    }

    public String postFormData(String url, Map<String, String> paramMap) throws IOException {
        FormBody.Builder builder = new FormBody.Builder();
        for (Map.Entry<String, String> entry : paramMap.entrySet()) {
            builder.add(entry.getKey(),entry.getValue());
        }
        FormBody formBody = builder.build();
        Request request = new Request.Builder()
                .url(url)
                .post(formBody)
//                .addHeader("token","aaaa")
                .build();

        Response response = client.newCall(request).execute();
        return response.body().string();
    }

}